package frame;

import java.awt.EventQueue;

import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;

import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.border.CompoundBorder;

import javax.swing.JFrame;

import service.ClienteService;

import bean.Message.Action;
import bean.Message;
import javax.swing.JList;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.JLayeredPane;
import javax.swing.AbstractListModel;

public class TelaEntrar extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField txtIP;
	private JTextField txtporta;
	private JTextField txtapelido;
	private Socket socket;
	private Message message;
	private ClienteService service;
	private JTextField textPartida;
	private JButton btnCriar;
	private JList listMenu;
	private JButton btnEntrar;
	private JButton btnSair;
	private String currentMatche = new String();

	public String getCurrentMatche() {
		return currentMatche;
	}

	public void setCurrentMatche(String currentMatche) {
		this.currentMatche = currentMatche;
	}

	/**
	 * Launch the application.
	 */

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TelaEntrar frame = new TelaEntrar();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	private void connected(Message message) {
		if (message.getText().equals("NÃO!")) {
			this.txtapelido.setText("");
			JOptionPane.showMessageDialog(this,
					"Conexão não realizada, tente outro nome!");
			return;
		}
		this.message = message;
		listMenu.setEnabled(true);
		btnCriar.setEnabled(true);
		textPartida.setEnabled(true);
		btnEntrar.setEnabled(false);
		txtapelido.setEnabled(false);
		txtIP.setEnabled(false);
		txtporta.setEnabled(false);

		// Menu menu = new Menu(txtapelido.getText());
		// menu.setVisible(true);
	}

	private class ListenerSocket implements Runnable {
		private TelaJogo jogo;
		private ObjectInputStream input;

		public ListenerSocket(Socket socket) {
			this.jogo = new TelaJogo(txtIP.getText(), Integer.parseInt(txtporta.getText()));
			try {
				this.input = new ObjectInputStream(socket.getInputStream());
			} catch (IOException ex) {
				// TODO Auto-generated catch block
				Logger.getLogger(TelaEntrar.class.getName()).log(
						Level.SEVERE, null, ex);
			}
		}

		@Override
		public void run() {

			Message message = null;

			try {
				while ((message = (Message) input.readObject()) != null) {
					bean.Message.Action action = message.getAction();
					System.out.println("RECEBEU! MENSAGEM: "
							+ message.getName() + " AÇÃO: "
							+ message.getAction());

					if (action.equals(Action.CONNECT)) {
						connected(message);
					} else if (action.equals(Action.DISCONNECT)) {
						// disconnected();
						// socket.close();
					} else if (action.equals(Action.PLAY)) {
						System.out.println("RECEBEU A RESPOSTA "
								+ message.getText());
						askMatches();
					} else if (action.equals(Action.NEW_USER)) {
						System.out.println("RECEBEU NOVO USUARIO!!!");
						if(message.getName().equals(txtapelido.getText())){
							jogo.setVisible(true);	
							currentMatche = message.getPartida();
							jogo.refresh(message);
							jogo.setPlayerName(message.getName());
							jogo.setPartida(message.getPartida());

						}else if(message.getPartida().equals(currentMatche)){
							jogo.refresh(message);
						}
					} else if (action.equals(Action.MATCHES)) {
						refreshMatches(message);
					} else if (action.equals(Action.CREATE_GAME)) {
						System.out.println("CREATE!!!");
						refreshMatches(message);
					}else if (action.equals(Action.GUESS)) {
						jogo.receiveGuess(message);
					}else if (action.equals(Action.NEW_WORD)) {
						jogo.receiveWord(message);
					}else if (action.equals(Action.NEXT_PLAYER)) {
						jogo.receiveNextPlayer(message);
					}else if (action.equals(Action.RODA)) {
						jogo.receiveRoda(message);
					}
				}
			} catch (ClassNotFoundException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				// disconnected();
			}

		}

		private void askMatches() {
			message = new Message();
			message.setAction(Action.MATCHES);
			message.setName(txtapelido.getName());

			String ip = txtIP.getText();
			String valorPorta = txtporta.getText();
			int porta = Integer.parseInt(valorPorta);

			service = new ClienteService(ip, porta);
			socket = service.connect();
			service.send(message);
			// TODO Auto-generated method stub
			
		}

		private void refreshMatches(Message message) {
			Set<String> names = message.getSetMatches();
			names.remove(message.getName());
			String[] array = (String[]) names.toArray(new String[names.size()]);
			System.out.println("TAMANHHO DA LISTA: " + array.length);

			listMenu.setListData(array);
			for (String item : array) {
				if (item.equalsIgnoreCase(textPartida.getText())) {
					textPartida.setText("");

				}
			}

		}

	}

	// Exemplo de código para excluir partida
	// Message message = new Message();
	// message.setName(txtapelido.getText());
	// message.setPartida(listMenu.getSelectedValue().toString());
	// message.setAction(Action.REMOVE_MATCH);
	// String ip = txtIP.getText();
	// String valorPorta = txtporta.getText();
	// int porta = Integer.parseInt(valorPorta);
	//
	// service = new ClienteService(ip, porta);
	// socket = service.connect();
	// service.send(message);

	public TelaEntrar() {
		this.currentMatche = "";
		setResizable(false);
		setBackground(new Color(240, 240, 240));
		setBounds(100, 100, 932, 553);
		JPanel panel = new JPanel();
		panel.setBorder(new CompoundBorder());
		panel.setBackground(new Color(0, 0, 51));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, GroupLayout.DEFAULT_SIZE, 926, Short.MAX_VALUE)
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
		);

		JLabel lblNewLabel = new JLabel("New label");
		lblNewLabel.setIcon(new ImageIcon("res/img/Logo.png"));

		JLabel label = new JLabel("");

		JSeparator separator = new JSeparator();
		
		JLayeredPane layeredPane = new JLayeredPane();
		layeredPane.setBorder(new LineBorder(Color.WHITE, 1, true));
		
		JLayeredPane layeredPane_1 = new JLayeredPane();
		layeredPane_1.setBorder(new LineBorder(Color.WHITE, 1, true));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createSequentialGroup()
							.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel.createSequentialGroup()
									.addGap(142)
									.addComponent(separator, GroupLayout.PREFERRED_SIZE, 305, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel.createSequentialGroup()
									.addContainerGap(10, Short.MAX_VALUE)
									.addComponent(layeredPane, GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(label)))
							.addGap(46))
						.addGroup(gl_panel.createSequentialGroup()
							.addContainerGap()
							.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 343, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)))
					.addComponent(layeredPane_1, GroupLayout.PREFERRED_SIZE, 405, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_panel.createSequentialGroup()
							.addContainerGap()
							.addComponent(layeredPane_1, GroupLayout.PREFERRED_SIZE, 428, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
							.addGroup(gl_panel.createSequentialGroup()
								.addGap(281)
								.addComponent(label)
								.addPreferredGap(ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
								.addComponent(separator, GroupLayout.PREFERRED_SIZE, 0, GroupLayout.PREFERRED_SIZE)
								.addGap(218))
							.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
								.addContainerGap()
								.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 195, GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
								.addComponent(layeredPane, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE))))
					.addContainerGap())
		);
		
				JLabel lblMenu = new JLabel("Menu");
				lblMenu.setBounds(10, 11, 59, 24);
				layeredPane_1.add(lblMenu);
				lblMenu.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 20));
				lblMenu.setForeground(Color.WHITE);
				
						JLabel lblCriarPartida = new JLabel("Criar Partida");
						lblCriarPartida.setBounds(10, 59, 95, 22);
						layeredPane_1.add(lblCriarPartida);
						lblCriarPartida.setForeground(Color.WHITE);
						lblCriarPartida
								.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 16));
						
								textPartida = new JTextField();
								textPartida.setBounds(10, 84, 126, 24);
								layeredPane_1.add(textPartida);
								textPartida.setEnabled(false);
								textPartida.setToolTipText("Digite seu endereço IP.");
								textPartida.setHorizontalAlignment(SwingConstants.CENTER);
								textPartida.setForeground(Color.BLACK);
								textPartida.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 13));
								textPartida.setColumns(10);
								textPartida.setBackground(Color.WHITE);
								
										btnCriar = new JButton("Criar");
										btnCriar.setBounds(146, 85, 67, 23);
										layeredPane_1.add(btnCriar);
										btnCriar.addActionListener(new ActionListener() {
											public void actionPerformed(ActionEvent e) {

												message = new Message();
												message.setAction(Action.CREATE_GAME);
												message.setName(txtapelido.getText());
												message.setPartida(textPartida.getText());
												String ip = txtIP.getText();
												String valorPorta = txtporta.getText();
												int porta = Integer.parseInt(valorPorta);

												service = new ClienteService(ip, porta);
												socket = service.connect();
												service.send(message);
												

											}
										});
										btnCriar.setEnabled(false);
										
												JButton btnJogar = new JButton("Jogar");
												btnJogar.setFont(new Font("Microsoft New Tai Lue", Font.PLAIN, 13));
												btnJogar.setBounds(142, 200, 71, 27);
												layeredPane_1.add(btnJogar);
												
														btnSair = new JButton("Sair");
														btnSair.setFont(new Font("Microsoft New Tai Lue", Font.PLAIN, 13));
														btnSair.setBounds(152, 234, 61, 27);
														layeredPane_1.add(btnSair);
														
																listMenu = new JList();
																listMenu.setModel(new AbstractListModel() {
																	String[] values = new String[] {};
																	public int getSize() {
																		return values.length;
																	}
																	public Object getElementAt(int index) {
																		return values[index];
																	}
																});
																listMenu.setBounds(10, 201, 126, 216);
																layeredPane_1.add(listMenu);
																listMenu.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 14));
																listMenu.setEnabled(false);
																
																JLabel lblSalas = new JLabel("Salas");
																lblSalas.setIcon(new ImageIcon("C:\\Users\\Ingrid\\Documents\\\u00CDtalo\\C\u00E9lula Acad\u00EAmica - S4I\\Projeto 2 - Roda - Roda\\Cliente\\res\\img\\door.png"));
																lblSalas.setForeground(Color.WHITE);
																lblSalas.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 18));
																lblSalas.setBounds(28, 166, 83, 24);
																layeredPane_1.add(lblSalas);
																
																JList list = new JList();
																list.setBounds(267, 203, 111, 134);
																layeredPane_1.add(list);
																
																JLabel lblRank = new JLabel("Rank");
																lblRank.setIcon(new ImageIcon("C:\\Users\\Ingrid\\Documents\\\u00CDtalo\\C\u00E9lula Acad\u00EAmica - S4I\\Projeto 2 - Roda - Roda\\Cliente\\res\\img\\cab_medalha.png"));
																lblRank.setForeground(Color.WHITE);
																lblRank.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 18));
																lblRank.setBounds(278, 158, 77, 40);
																layeredPane_1.add(lblRank);
																
																JSeparator separator_2 = new JSeparator();
																separator_2.setBounds(10, 134, 385, 2);
																layeredPane_1.add(separator_2);
												btnJogar.addActionListener(new ActionListener() {
													public void actionPerformed(ActionEvent arg0) {
														if (listMenu.getSelectedIndex() > -1) {
															Message message = new Message();
															message.setName(txtapelido.getText());
															message.setPartida(listMenu.getSelectedValue().toString());
															message.setAction(Action.PLAY);
															String ip = txtIP.getText();
															String valorPorta = txtporta.getText();
															int porta = Integer.parseInt(valorPorta);

															service = new ClienteService(ip, porta);
															socket = service.connect();
															service.send(message);
														}
													}
												});
		
				JLabel lblApelido = new JLabel("Apelido :");
				lblApelido.setBounds(60, 164, 121, 49);
				layeredPane.add(lblApelido);
				lblApelido.setIcon(new ImageIcon("res/img/Usu\u00E1rio-HM.png"));
				lblApelido.setForeground(Color.WHITE);
				lblApelido.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 16));
				
						txtapelido = new JTextField();
						txtapelido.setBounds(191, 176, 126, 24);
						layeredPane.add(txtapelido);
						txtapelido.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent arg0) {

							}
						});
						txtapelido.setToolTipText("Digite seu endere\u00E7o IP.");
						txtapelido.setHorizontalAlignment(SwingConstants.CENTER);
						txtapelido.setForeground(Color.BLACK);
						txtapelido.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 13));
						txtapelido.setColumns(10);
						txtapelido.setBackground(Color.WHITE);
						
								btnEntrar = new JButton("");
								btnEntrar.setBounds(327, 168, 84, 32);
								layeredPane.add(btnEntrar);
								btnEntrar.addActionListener(new ActionListener() {
									public void actionPerformed(ActionEvent e) {
										System.out.println("NOME");

										String name = txtapelido.getText();

										System.out.println("O nome é: " + name);
										if (!name.isEmpty()) {
											message = new Message();
											message.setAction(Action.CONNECT);
											message.setName(name);

											String ip = txtIP.getText();
											String valorPorta = txtporta.getText();
											int porta = Integer.parseInt(valorPorta);

											service = new ClienteService(ip, porta);
											socket = service.connect();

											Thread thread = new Thread(new ListenerSocket(socket));
											thread.start();

											service.send(message);
											System.out.println("foi 1");

										}
									}
								});
								
										btnEntrar.setIcon(new ImageIcon("res/img/bth_entrar.png"));
										
												JSeparator separator_1 = new JSeparator();
												separator_1.setBounds(10, 144, 419, 2);
												layeredPane.add(separator_1);
												
														JLabel lblIp = new JLabel("Endere\u00E7o IP :");
														lblIp.setBounds(34, 44, 147, 50);
														layeredPane.add(lblIp);
														
														lblIp.setIcon(new ImageIcon("res/img/reverse-ip.png"));
														lblIp.setForeground(Color.WHITE);
														lblIp.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 16));
														lblIp.setBackground(new Color(240, 240, 240));
														lblIp.setToolTipText("");
														
																JLabel lblSenha = new JLabel("Porta :");
																lblSenha.setBounds(82, 92, 99, 41);
																layeredPane.add(lblSenha);
																lblSenha.setIcon(new ImageIcon("res/img/conexao.png"));
																lblSenha.setForeground(Color.WHITE);
																lblSenha.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 16));
																
																		txtIP = new JTextField();
																		txtIP.setBounds(191, 57, 126, 24);
																		layeredPane.add(txtIP);
																		txtIP.setText("localhost");
																		txtIP.setHorizontalAlignment(SwingConstants.CENTER);
																		txtIP.setForeground(new Color(0, 0, 0));
																		txtIP.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 13));
																		txtIP.setToolTipText("Digite seu endere\u00E7o IP.");
																		txtIP.setBackground(Color.WHITE);
																		txtIP.setColumns(10);
																		
																				txtporta = new JTextField();
																				txtporta.setBounds(191, 105, 126, 24);
																				layeredPane.add(txtporta);
																				txtporta.setText("5556");
																				txtporta.setToolTipText("Digite seu endere\u00E7o IP.");
																				txtporta.setHorizontalAlignment(SwingConstants.CENTER);
																				txtporta.setForeground(Color.BLACK);
																				txtporta.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 13));
																				txtporta.setColumns(10);
																				txtporta.setBackground(Color.WHITE);
																				
																				JLabel lblLogin = new JLabel("Login");
																				lblLogin.setBounds(10, 9, 71, 24);
																				layeredPane.add(lblLogin);
																				lblLogin.setForeground(Color.WHITE);
																				lblLogin.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 20));
		panel.setLayout(gl_panel);
		getContentPane().setLayout(groupLayout);

	}
}
